package sites.manager.admin.login;

import com.jfinal.aop.Inject;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Ret;
import sites.manager.admin.account.AccountService;
import sites.manager.common.kit.SiteInfo;
import sites.manager.common.model.Account;

import java.util.Date;

public class LoginService {

    @Inject
    private AccountService accountSrv;

    /**
     * 用户登录
     * @param name	用户名
     * @param pwd	密码
     * @return ret
     */
    public Ret doLogin(String name, String pwd){
        Ret ret = Ret.fail();

        //验证用户是否存在
        Account account = accountSrv.getByName(name);
        if(account == null){
            ret.set(SiteInfo.msgKey, "该用户不存在！");
            return ret;
        }

        //查看用户状态
        String status = account.getStatus();
        if(SiteInfo.statusDel.equals(status)){
            ret.set(SiteInfo.msgKey, "用户不可用！");
            return ret;
        }
        if(SiteInfo.statusLock.equals(status)){
            ret.set(SiteInfo.msgKey, "用户已锁定！");
            return ret;
        }

        //验证密码是否正确
        pwd = HashKit.md5(pwd);
        String password = account.getPassword();
        if(!password.equals(pwd)){
            ret.set(SiteInfo.msgKey, "密码错误！");
            int errorCount = account.getErrorCount()==null ? 0 : account.getErrorCount();
            errorCount++;
            account.setErrorCount(errorCount);
            if(errorCount >= SiteInfo.maxErrorCount){
                account.setStatus(SiteInfo.statusLock);
            }
            account.update();//记录错误次数
            return ret;
        }

        //通过所有验证后登录成功
        ret.setOk();
        account.setLoginTime(new Date());
        account.update();
        ret.set(SiteInfo.account, account);

        //查询用户权限，查询后自动启用缓存了
        //permSrv.getAccountPerm(account.getId());

        return ret;
    }

}
